package com.iaz.tech.tools.common.flow.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iaz.tech.tools.common.flow.IFlowAble;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 *  For 循环语句
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class ForFlow extends FlowsGroup {
	/**
      * 日志
      */
	private final static Logger logger = (Logger) LoggerFactory.getLogger(ForFlow.class);
	private List<IFlowAble> boundaries = new ArrayList<IFlowAble>();

	/**
     * 执行流程
     */
    @Override
    public Object executeFlow(Object property) {
        Object result = null;
        try {
            if (this.boundaries == null || this.boundaries.isEmpty()) {
                logger.warn("ForFlow boundaries is null or empty");
                return result;
            }
            if (this.boundaries.size() != 3) {
                logger.warn("ForFlow boundaries size must be 3");
                return result;
            }

            IFlowAble initFlow = this.boundaries.get(0);
            IFlowAble conditionFlow = this.boundaries.get(1);
            IFlowAble incrementFlow = this.boundaries.get(2);

            // 初始化
            initFlow.executeFlow(property);
            // 循环条件
            while ((Boolean) conditionFlow.executeFlow(property)) {
                // 执行循环体
                result = super.executeFlow(property);
                // 循环变量增量
                incrementFlow.executeFlow(property);
            }

        } catch (Exception e) {
            logger.error("ForFlow executeFlow error", e);
        }
        return result;
    }

}
